<template>
    <div>
        <div class="left" @click="back2">
            <van-icon name="arrow-left" />
        </div>
        <div class="right">
            <van-icon name="search" />
        </div>
        <div class="gwc">
            <span class="gwc-wz">购物车</span>
        </div>

        <van-empty v-if="cartList.length === 0" description="空空如也" />

        <div class="cart-items">
            <van-swipe-cell v-for="(cartItem, index) in cartList" :key="cartItem.id">
                <div class="cart-item">
                    <!-- 左上角圆圈 -->

                    <div class="yq">
                        <van-checkbox v-model="cartItem.checked" checked-color="#ee0a24" />
                    </div>
                    <van-card
                            :num="cartItem.cartNum"
                            :price="cartItem.costPrice"
                            :desc="cartItem.productInfo.storeInfo"
                            :title="cartItem.productInfo.storeName"
                            :thumb="'http://192.168.40.177:8008/api'+cartItem.productInfo.image"
                    >
                        <template #tags>
                            <van-tag plain type="danger">{{cartItem.productInfo.attrInfo.sku}}</van-tag>
                        </template>
                        <!-- 步进器 -->
                        <template #footer>
                            <van-stepper
                                    v-model="cartItem.cartNum"
                                    input-width="40px"
                                    button-size="32px"
                                    @change="updateTotalPrice"
                            />
                        </template>
                    </van-card>
                </div>
                <template #right>
                    <cartzj
                            :item-id="cartItem.id"
                            @delete="getdelcart"
                    />
                </template>
            </van-swipe-cell>
        </div>

        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit">
            <van-checkbox v-model="allChecked">全选</van-checkbox>
            <template #tip>
                向左滑动商品可删除该商品！<span></span>
            </template>
        </van-submit-bar>
    </div>
</template>

<script>
    import { Empty } from 'vant';
    import cartzj from "@/components/cartzj";
    import TabBar from "@/components/TabBar";
    import { Toast } from 'vant';
    import axios from 'axios';
    import { getcart,delCart} from "@/api/cart";
    import topBack from "@/components/topBack";
    export default {
        name: "cart",
        components:{
            TabBar,
            cartzj
        },
        data() {
            return {
                list: [], //获取点击的id数组
                cartList: [],
                allChecked: false,
            }
        },
        computed: {
            // 计算合计金额
            totalPrice() {
                return this.cartList.reduce((total, item) => {
                    return item.checked ? total + (item.costPrice * item.cartNum) : total;
                }, 0) * 100; // Vant的SubmitBar组件要求价格单位为分
            }
        },
        watch: {
            // 监听购物车列表变化，更新全选状态
            cartList: {
                handler() {
                    this.updateAllCheckedStatus();
                },
                deep: true
            },
            // 监听全选状态变化
            allChecked(value) {
                this.cartList.forEach(item => {
                    item.checked = value;
                });
            }
        },
        created() {
            this.getcart();
        },
        methods: {
            back2() {
                this.$router.go(-1);
            },
            getcart() {
                getcart().then(res => {
                    if (res && res.data && res.data.data && res.data.data.valid) {
                        const validItems = res.data.data.valid;
                        // 为每个商品添加选中状态
                        this.cartList = validItems.map(item => ({
                            ...item,
                            checked: true // 默认选中
                        }));
                        this.updateAllCheckedStatus();
                    }
                })
            },
            // 更新全选状态
            updateAllCheckedStatus() {
                this.allChecked = this.cartList.length > 0 && this.cartList.every(item => item.checked);
            },
            // 删除商品
            getdelcart(id) {
                let list = []
                list.push(id)
                const requestData = JSON.stringify({ids:list})
                delCart(requestData).then(res => {
                    if (res) {
                        this.getcart()
                        this.$toast.success('删除成功');
                    }

                })
            },
            // 更新合计金额
            updateTotalPrice() {
                // 重新计算合计金额
                this.$forceUpdate();
            },
            // 提交订单
            onSubmit() {
                const selectedItems = this.cartList.filter(item => item.checked);
                if (selectedItems.length === 0) {
                    Toast.fail('请选择商品');
                    return;
                }
                // 这里可以跳转到订单确认页或提交订单
                console.log('提交订单:', selectedItems);
                this.$router.push({ name: 'OrderConfirm', params: { items: selectedItems } });
            }
        }
    }
</script>

<style>
    .yq {
        position: absolute;
        z-index: 99;
        margin-left: 20px;
        margin-top: 10px;
    }

    .goods-card {
        margin: 0;
        background-color: white;
    }



    .yq {
        position: absolute;
        z-index: 99;
        margin-left: 20px;
        margin-top: 10px;
    }

    .van-card {
        padding: 20px !important;
    }

    .lm {
        margin: 10px;
        position: relative;
    }

    .gwc-wz {
        display: flex;
        justify-content: center;
        font-size: 18px;
    }

    .gwc {
        background-color: white;
        padding: 15px 0;
        border-bottom: 1px solid rgba(208, 209, 253, 0.19);
    }

    .right {
        position: absolute;
        padding: 15px 16px;
        position: absolute;
        font-size: 20px;
        color: #8aa3ef;
        right: 0;
    }

    .left {
        position: absolute;
        padding: 16px;
    }

    .cart-items {
        padding-bottom: 60px; /* 为底部栏留出空间 */
    }

    .cart-item {
        margin-bottom: 10px;
    }
</style>